package com.udf.hive.udf.string;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;

/**
 * add jar /home/isuhadoop/tests/udf/md5pwd.jar
 * create temporary function md5 as 'com.analysys.encrypt.utils.Md5pwd';
 * drop temporary function md5
 *  
 * hive udf函数Md5加密工具  
 * Returns the MD5 hash of argument
 * 
 * @author root
 *
 */
@Description(name = "udfMD5",value = "_FUNC_(string) - MD5",
    		 extended = "Example:\n"
    				  + "  > SELECT MD5('hashme') FROM tmp;\n")
public class UDFMD5 extends UDF {

	  // 全局数组
	    private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
	            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	    public UDFMD5() {
	    }

	    // 返回形式为数字跟字符串
	    private static String byteToArrayString(byte bByte) {
	        int iRet = bByte;
	        // System.out.println("iRet="+iRet);
	        if (iRet < 0) {
	            iRet += 256;
	        }
	        int iD1 = iRet / 16;
	        int iD2 = iRet % 16;
	        return strDigits[iD1] + strDigits[iD2];
	    }

	    // 返回形式只为数字
	    private static String byteToNum(byte bByte) {
	        int iRet = bByte;
	        System.out.println("iRet1=" + iRet);
	        if (iRet < 0) {
	            iRet += 256;
	        }
	        return String.valueOf(iRet);
	    }

	    // 转换字节数组为16进制字串
	    private static String byteToString(byte[] bByte) {
	        StringBuffer sBuffer = new StringBuffer();
	        for (int i = 0; i < bByte.length; i++) {
	            sBuffer.append(byteToArrayString(bByte[i]));
	        }
	        return sBuffer.toString();
	    }
	    /**
	     * @description param==null return null
	     * 				param=="null" return 37a6259cc0c1dae299a7866489dff0bd
	     * 				param=""	return d41d8cd98f00b204e9800998ecf8427e
	     * @param strObj
	     * @return
	     */
	    public static String GetMD5Code(String strObj) {
	        String resultString = null;
	        if(strObj==null){
	        	return null;
	        }
	        try {
	            resultString = new String(strObj);
	            MessageDigest md = MessageDigest.getInstance("MD5");
	            // md.digest() 该函数返回值为存放哈希值结果的byte数组
	            resultString = byteToString(md.digest(strObj.getBytes()));
	        } catch (NoSuchAlgorithmException ex) {
	            ex.printStackTrace();
	        }
	        return resultString;
	    }

	    public String evaluate(String str){
	        String s=GetMD5Code(str);
	        return s;
	    }
	    
	    public static void main(String[] args) {
	    	System.out.println(GetMD5Code("10581b613d5db685"));//d41d8cd98f00b204e9800998ecf8427e
	    	System.out.println(GetMD5Code("null"));//37a6259cc0c1dae299a7866489dff0bd
	    	System.out.println(GetMD5Code(null));//null
		}
	    
	}